package com.cenntro.nearr.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import com.cenntro.nearr.base.BaseController;
import com.cenntro.nearr.common.PageResult;
import com.cenntro.nearr.common.Result;
import com.cenntro.nearr.service.AddressService;
import com.cenntro.nearr.service.LocationService;
import com.cenntro.nearr.vo.AddressVO;
import com.cenntro.nearr.vo.LocationVO;
import com.google.common.collect.Maps;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;


//@RestController
@Controller
@RequestMapping("/address")
public class AddressController extends BaseController{

	
	private Logger LOG = LoggerFactory.getLogger(AddressController.class);
	
	@Value("${filepath}")
	private String path;
	@Value("${domain}")
	private String domain;
	
	@Autowired
	private AddressService addressService;
	@Autowired
	private LocationService locationService;

	
	@CrossOrigin
//	@ApiOperation(value = "查找", notes = "根据ID查找")
	@RequestMapping(value = "/test")
	public String test() {
		return "index";
	}
	@CrossOrigin
	@RequestMapping(value = "/deleteById")
	@ResponseBody
	public Result delete(Integer addressId){
		addressService.deleteById(addressId);
		return Result.ok();
	}
	
	@CrossOrigin
	@ApiOperation(value = "查找", notes = "根据ID查找")
	@RequestMapping(value = "/selectById")
	@ResponseBody
	public Result selectById(Integer addressId) {
		LOG.info("selectById id{}", addressId);
		AddressVO addr = addressService.selectById(addressId);
		LocationVO location = locationService.selectById(addr.getLocationId());
		//BeanUtils.copyProperties(location, addr);
		addr.setAddress(location.getAddress());
		addr.setCountry(location.getCountry());
		addr.setState(location.getState());
		addr.setCity(location.getCity());
		addr.setZipCode(location.getZipCode());
		addr.setBuildingType(location.getBuildingType());
		addr.setLat(location.getLat());
		addr.setLng(location.getLng());
		addr.setLocationId(location.getLocationId());
		String picture = location.getPicture();
		
		addr.setPicture(picture);
		return Result.ok(addr);
	}
	
	@CrossOrigin
	@ApiIgnore
	@RequestMapping(value = "/selectPage")
	@ResponseBody
	public Result selectPage(AddressVO addr) {
		int count = addressService.selectCount(addr);
		if(count > 0){
			List<AddressVO> list = addressService.selectPage(addr);
			Map<Integer, LocationVO> map = Maps.newHashMap();
			for (AddressVO vo : list){
				LocationVO loca = map.get(vo.getLocationId());
				if (loca == null){
					loca = locationService.selectById(vo.getLocationId());
					map.put(vo.getLocationId(), loca);
				}
				vo.setAddress(loca.getAddress());
				vo.setCountry(loca.getCountry());
				vo.setState(loca.getState());
				vo.setCity(loca.getCity());
				vo.setZipCode(loca.getZipCode());
				vo.setBuildingType(loca.getBuildingType());
				vo.setLat(loca.getLat());
				vo.setLng(loca.getLng());
			}
			return PageResult.ok(list, count);
		}
		return PageResult.ok();
	}
	
	@CrossOrigin
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Result save(AddressVO adddress, @RequestParam(value = "files") MultipartFile[] files){
		String picture= "";
		FileOutputStream out = null;
		if (files != null){
			for (MultipartFile file : files){
				String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
				try{
					String str = getpath(suffix);
					String dir = str.substring(0, str.lastIndexOf("/"));
					File f = new File(dir);
					if (!f.exists()){
						f.mkdirs();
					}
					out = new FileOutputStream(str);
					FileCopyUtils.copy(file.getInputStream(), out);
					if (picture.length() > 0){
						picture += "&&&";
					}
					picture += domain + str.replaceAll("/opt/data/upload/", "upload/");
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		if(StringUtils.isNotBlank(picture)){
			if (StringUtils.isNotBlank(adddress.getPicture())){
				adddress.setPicture(adddress.getPicture() + "&&&" + picture);
			}else{
				adddress.setPicture(picture);
			}
		}
		
		adddress = addressService.saveOrUpdate(adddress);
		return Result.ok(adddress);
	}
	
	

	
	private String getpath(String suffix){
		Random r = new Random();
		String ranstr = String.format("%05d", r.nextInt(10000));
		
		String str = DateFormatUtils.format(new Date(), "yyyyMMdd");
		String path = this.path + str + "/" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "-" + ranstr + suffix;
		LOG.info("path:" + path);
		return path;
	}
	
	
}
